package nsu.edu.zsq.service.impl.sys;

import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import nsu.edu.zsq.bean.SchOrg;
import nsu.edu.zsq.bean.SchOrgExample;
import nsu.edu.zsq.common.RequestHolder;
import nsu.edu.zsq.dao.SchOrgMapper;
import nsu.edu.zsq.exception.ParamException;
import nsu.edu.zsq.param.SchOrgParam;
import nsu.edu.zsq.service.sys.SchOrgService;
import nsu.edu.zsq.service.sys.SysLogService;
import nsu.edu.zsq.util.BeanValidator;
import nsu.edu.zsq.util.JsonMapper;
import nsu.edu.zsq.util.SchOrgUtil;

/** 
* Description: 学校组织（院系）的service实现类<br>
*/
@Service
public class SchOrgServiceImpl implements SchOrgService {
    
    @Autowired
    private SchOrgMapper schOrgMapper;
    @Autowired
    private SysLogService sysLogService;
    
    @Override
    public SchOrg getSchOrg(int orgId) {
        SchOrg schOrg = schOrgMapper.selectByPrimaryKey(orgId);
        return schOrg;
    }

    @Override
    public List<SchOrg> listSchOrg() {
        SchOrgExample example = new SchOrgExample();
        // 根据sort降序排列
        example.setOrderByClause("sort DESC");
        List<SchOrg> schOrgs = schOrgMapper.selectByExample(example);
        return schOrgs;
    }
    
    @Override
    public List<SchOrgParam> listSchOrgParam() {
        List<SchOrgParam> listSchOrgParam = schOrgMapper.listSchOrgParam();
        return listSchOrgParam;
    }
    
    @Override
    public String listSchOrgParamWithTree() {
        List<SchOrgParam> listSchOrgParam = listSchOrgParam();
        // 转换为树结构
        List<SchOrgParam> schOrgParamToTree = SchOrgUtil.schOrgParamToTree(listSchOrgParam);
        return JsonMapper.obj2String(schOrgParamToTree);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveSchOrg(SchOrg schOrg) {
        BeanValidator.check(schOrg);
        if (checkExist(schOrg.getOrgName())) {
            throw new ParamException("该院系已经存在");
        }
		/*
		 * schOrg.setOperator(RequestHolder.getCurrentSysUser().getAccount());
		 * schOrg.setOperatorTime(new Date());
		 */
        // 1.添加院系
        schOrgMapper.insertSelective(schOrg);
        
		/*
		 * // 2.添加日志 String instruction = "院系管理-添加院系";
		 * sysLogService.saveSysLogBySysUser(null, schOrg, instruction);
		 */
    }
    
    /**
     * 根据院系名称检查该院系是否已经存在
     * @param orgName 院系名称
     * @return boolean true:存在 false：不存在
     */
    private boolean checkExist(String orgName) {
        return schOrgMapper.countByOrgName(orgName) > 0;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteBatchSchOrg(int[] orgIds) {
        boolean flag = false;
        // 1.首先判断所选院系下面是否含有未选的子院系
        for (int orgId : orgIds) {
            List<SchOrg> listSchOrgChildren = schOrgMapper.listSchOrgChildrenByPrimaryKey(orgId);
            for (SchOrg schOrg : listSchOrgChildren) {
                for (int i = 0; i < orgIds.length; i++) {
                    if (orgIds[i] == schOrg.getId()) {
                        flag = true;
                        break;
                    }
                }
                if (!flag) {
                    throw new ParamException("所选院系下有未选的子院系，不能删除");
                } else {
                    flag = false;
                }
            }
            // 2.判断该院系下面是否存在专业信息
            if (checkHasSchMajor(orgId)) {
                throw new ParamException("所选院系下存在专业信息，不能删除");
            }
        }
        // TODO:该院系下面是否存在其它依赖？系别、学生、老师等
        
        List<SchOrg> before = schOrgMapper.listSchOrgByOrgIds(orgIds);
        for (int orgId : orgIds) {
            // 3.删除院系
            schOrgMapper.deleteByPrimaryKey(orgId);
        }
        
		/*
		 * // 4.添加日志 String instruction = "院系管理-批量删除";
		 * sysLogService.saveSysLogBySysUser(before, null, instruction);
		 */
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteSchOrg(int orgId) {
        // 1.判断该院系是否有子院系
        int schOrgChildrenNum = schOrgMapper.countSchOrgChildrenByPrimaryKey(orgId);
        if (schOrgChildrenNum > 0) {
            throw new ParamException("该院系下有子院系，不能删除");
        }
        // 2.判断该院系下面是否存在专业信息
        if (checkHasSchMajor(orgId)) {
            throw new ParamException("该院系下存在专业信息，不能删除");
        }
        // TODO:该院系下面是否存在其它依赖？系别、学生、老师等
        
        SchOrg before = schOrgMapper.selectByPrimaryKey(orgId);
        // 3.删除该院系
        schOrgMapper.deleteByPrimaryKey(orgId);
        
		/*
		 * // 4.添加日志 String instruction = "院系管理-单个删除";
		 * sysLogService.saveSysLogBySysUser(before, null, instruction);
		 */
    }

    /**
     * 根据院系id检查该院系下面是否存在专业信息（SchMajor）
     * @param orgId 院系id
     * @return boolean true:存在 false:不存在
     */
    private boolean checkHasSchMajor(int orgId) {
        return schOrgMapper.countSchMajorByOrgId(orgId) > 0;
    }
    
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateSchOrg(SchOrg schOrg) {
        SchOrg before = getSchOrg(schOrg.getId());
		/*
		 * schOrg.setOperator(RequestHolder.getCurrentSysUser().getAccount());
		 * schOrg.setOperatorTime(new Date());
		 */
        // 1.更新
        schOrgMapper.updateByPrimaryKeySelective(schOrg);
        
		/*
		 * // 2.添加日志 SchOrg after = new SchOrg(); // 对象拷贝
		 * BeanUtils.copyProperties(before, after); after.setId(schOrg.getId());
		 * after.setOrgName(schOrg.getOrgName()); after.setSort(schOrg.getSort());
		 * after.setOperator(schOrg.getOperator());
		 * after.setOperatorTime(schOrg.getOperatorTime()); String instruction =
		 * "院系管理-编辑院系信息"; sysLogService.saveSysLogBySysUser(before, after, instruction);
		 */
    }

}
